﻿using System;
using System.Collections.Generic;
using System.Web;


namespace CCPSIP.Message
{
    /// <summary>CCPSIP_039：設定訊息提醒(Push通知)狀態 API</summary>
    /// idHeader = 裝置 UUID 前八碼。
    /// checkcode = 裝置限時驗證碼。
    /// ChatID = 聊天ID(對方帳號或ClientGID)。
    /// OnOff = 訊息提醒On或Off，設定值為 ("ON", "OFF")。

    public class notify_set : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            HttpRequest req = context.Request;
            HttpResponse resp = context.Response;
            resp.ContentType = "text/plain";
            resp.ContentEncoding = System.Text.Encoding.UTF8;
            DateTime reqTime = DateTime.Now;
            string resultStr = "";


            try
            {
                //【01】取得POST參數，驗證身分
                //
                string idHeader = req.Form["idHeader"];
                string checkcode = req.Form["checkcode"];
                string ChatID = req.Form["ChatID"]; //聊天ID(對方帳號或ClientGID)
                string OnOffStr = req.Form["OnOff"];//訊息提醒On或Off

                SipUserInfo userInfo = SipKit.GetUserInfo(idHeader, checkcode, req);
                if (userInfo == null)
                {
                    throw new Exception("Error_01: Cannot identify this device");//無法識別此裝置
                }

                try
                {
                    ChatID = ChatID.Trim();
                    OnOffStr = OnOffStr.Trim().ToUpper();

                    if (ChatID.Length < 5)
                        throw new Exception();
                }
                catch (Exception ex)
                {
                    ChrisKit.SkipVar(ex);
                    throw new Exception("Error_02: Parameter Error");//參數錯誤
                }

                bool OnOff = true;
                if (OnOffStr == "OFF")
                {
                    OnOff = false;
                }
                else
                {
                    OnOffStr = "ON";
                }


                //【02】設定訊息提醒狀態
                //
                OracleKitMsg.SetMsgNotify(userInfo.SIP_Num, ChatID, OnOff);


                resultStr = OnOffStr;
            }
            catch (Exception ex)
            {
                resp.ContentType = "application/xml";
                resultStr = ChrisKit.Ex2Xml(ex, false);
            }
            finally
            {
                int contentLength = resp.ContentEncoding.GetByteCount(resultStr);
                resp.AppendHeader("Content-Length", contentLength.ToString());
                resp.Write(resultStr);
                resp.Flush();
                resp.Close();
            }
        }


        public bool IsReusable
        {
            get
            {
                return false;
            }
        }

    }
}
